#!/usr/bin/env python
# -*- coding:utf-8 -*-

# import
import os
import sys
import threading
import time
import datetime
import urllib2

# common
from common.log import log
from common.db.db import Db
from common.const import Const
from common.util import Util

defaultencoding = 'utf-8'
if sys.getdefaultencoding() != defaultencoding:
    reload(sys)
    sys.setdefaultencoding(defaultencoding)


class System:
    '''
    系统相关
    '''

    def __init__(self):
        '''初始化'''
        log.debug('System init')

        # 系统变量获取
        env = os.environ
        self.vis_root_path = '/opt/local/vis'
        self.vis_upload_path = '/mnt/upload/vis'
        try:
            self.vis_root_path = env['VIS_ROOT_PATH']
        except Exception, e:
            pass
        try:
            self.vis_upload_path = env['VIS_UPLOAD_PATH']
        except Exception, e:
            pass

        self.upgrade_server_address = Util.get_config_value(
            'UPGRADE_SERVER_ADDRESS')
        upgrade_server_port_str = Util.get_config_value('UPGRADE_SERVER_PORT')
        self.upgrade_server_port = int(
            upgrade_server_port_str) if upgrade_server_port_str else 8081

        self.data_backup_th = threading.Thread(target=self.data_backup_process)
        self.data_backup_th.setDaemon(True)
        self.data_backup_th.start()

    def data_backup_process(self):
        '''数据备份'''
        log.debug('data_backup_process')

        while (True):
            cur_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
            cmd = ('cd %s/manager/data;mkdir -p bak;'
                   'cp -f vis.s3db bak/vis.%s.s3db') % (
                self.vis_root_path, cur_time)
            os.system(cmd)
            log.debug('db backup success')
            time.sleep(60 * 60 * 24)

    def query_device(self):
        '''查询设备信息'''
        log.debug('query_device')

        ret_code = 1000
        ret_data = None

        name = 'VIS流媒体服务器'
        sn = Util.query_sn()
        version = Util.query_version()

        ret_data = '{"name":"%s","sn":"%s","version":"%s"}' % (
            name, sn, version)

        return ret_code, ret_data

    def query_system(self):
        '''查询系统信息'''
        log.debug('query_system')

        ret_code = 1000
        ret_data = None

        seconds = Util.get_runtime()
        m, s = divmod(seconds, 60)
        h, m = divmod(m, 60)
        runtime = '%d:%02d:%02d' % (h, m, s)

        cpu_usage = Util.get_cpu_usage()

        disk_used, disk_total, disk_usage = Util.get_disk_usage()

        mem_used, mem_total, mem_usage = Util.get_mem_usage()

        ret_data = ('{"runtime":"%s","cpu_usage":"%s","disk_used":"%s",'
                    '"disk_total":"%s","disk_usage":"%s","mem_used":"%s",'
                    '"mem_total":"%s","mem_usage":"%s"}') % (
                        runtime, cpu_usage, disk_used, disk_total,
                        disk_usage, mem_used, mem_total, mem_usage)

        return ret_code, ret_data

    def restart(self):
        '''服务重启'''
        log.debug('restart')

        ret_code = 1000
        ret_data = None

        Util.restart()

        return ret_code, ret_data

    def upgrade(self):
        '''版本升级'''
        log.debug('upgrade')

        ret_code = 1000
        ret_data = None

        Util.restart()

        return ret_code, ret_data

    def query_latest_version(self):
        '''查询最新版本'''
        log.debug('query_latest_version')

        ret_code = 1000
        ret_data = None

        version = ''
        cur_version = Util.query_version()

        # 查询最新版本信息
        url = ('http://%s:%d/query_latest?device=%s') % (
            self.upgrade_server_address,
            self.upgrade_server_port,
            Const.DEVICE_TYPE)
        try:
            request = urllib2.Request(url)
            response = urllib2.urlopen(request)
            server_version = response.read()

            cur_version_list = cur_version.split('.')
            server_version_list = server_version.split('.')

            for i in range(len(cur_version_list)):
                if i == 2:
                    continue
                if server_version_list[i] > cur_version_list[i]:
                    version = server_version
                    break
        except Exception, e:
            log.debug("Cannot get new version")

        ret_data = ('{"version":"%s"}') % (version)

        return ret_code, ret_data

    def download_upgrade_file(self, version):
        '''在线下载版本'''
        log.debug('download_upgrade_file, version:%s' % (version))

        ret_code = 1000
        ret_data = None

        download_url = ''
        # 在线升级
        if version == 'latest':
            # 升级为最新版本
            download_url = 'http://%s:%d/update_latest?device=%s' % (
                self.upgrade_server_address,
                self.upgrade_server_port,
                Const.DEVICE_TYPE)
        else:
            # 升级指定版本
            download_url = 'http://%s:%d/update_given?device=%s&version=%s' % (
                self.upgrade_server_address,
                self.upgrade_server_port,
                Const.DEVICE_TYPE,
                version)

        try:
            if download_url:
                request = urllib2.Request(download_url)
                request.add_header('Content-Type', 'application/octet-stream')
                response = urllib2.urlopen(request, data='')
                filename = response.headers['Content-Disposition'].split('"')[
                    1]
                with open('%s/%s' % (self.vis_upload_path, filename),
                          'wb') as f:
                    f.write(response.read())
        except Exception, e:
            log.debug('upgrade failed')
            ret_code = 1011
            ret_data = '{"info": "upgrade failed."}'

        return ret_code, ret_data
